"""
库存相关服务
"""
from app.models.inventory import InventoryRecord, InventoryType
from app.models.product import Product, ProductVariant
from app.extensions import db
from app.utils.errors import NotFoundError, ValidationError
from flask_jwt_extended import get_jwt_identity

class InventoryService:
    """库存服务类"""
    
    @staticmethod
    def get_inventory_records(page=1, per_page=20, record_type=None, 
                            product_id=None, variant_id=None, 
                            start_date=None, end_date=None,
                            sort_by='created_at', sort_order='desc'):
        """获取库存记录"""
        query = InventoryRecord.query
        
        # 过滤条件
        if record_type:
            query = query.filter_by(type=record_type)
        
        if product_id:
            query = query.filter_by(product_id=product_id)
        
        if variant_id:
            query = query.filter_by(variant_id=variant_id)
        
        if start_date:
            query = query.filter(InventoryRecord.created_at >= start_date)
        
        if end_date:
            query = query.filter(InventoryRecord.created_at <= end_date)
        
        # 排序
        if sort_order == 'desc':
            query = query.order_by(getattr(InventoryRecord, sort_by).desc())
        else:
            query = query.order_by(getattr(InventoryRecord, sort_by).asc())
        
        # 分页
        pagination = query.paginate(page=page, per_page=per_page)
        
        return pagination
    
    @staticmethod
    def get_current_stock(product_id=None, variant_id=None):
        """获取当前库存"""
        if variant_id:
            variant = ProductVariant.query.get(variant_id)
            if not variant:
                raise NotFoundError("商品变体不存在")
            
            return {
                "product_id": variant.product_id,
                "variant_id": variant.id,
                "stock": variant.stock,
                "specifications": variant.specifications
            }
        
        elif product_id:
            product = Product.query.get(product_id)
            if not product:
                raise NotFoundError("商品不存在")
            
            # 获取所有变体
            variants = ProductVariant.query.filter_by(product_id=product_id).all()
            
            return {
                "product_id": product.id,
                "product_name": product.name,
                "stock": product.stock,
                "variants": [
                    {
                        "variant_id": v.id,
                        "specifications": v.specifications,
                        "stock": v.stock
                    } for v in variants
                ]
            }
        
        else:
            raise ValidationError("请提供商品ID或变体ID")
    
    @staticmethod
    def stock_in(product_id, quantity, variant_id=None, notes='', operator_id=None):
        """入库操作"""
        if not product_id or not quantity or quantity <= 0:
            raise ValidationError("请提供有效的商品ID和入库数量")
        
        try:
            # 更新库存
            if variant_id:
                variant = ProductVariant.query.get(variant_id)
                if not variant:
                    raise NotFoundError("商品变体不存在")
                
                variant.stock += quantity
                product = variant.product
            else:
                product = Product.query.get(product_id)
                if not product:
                    raise NotFoundError("商品不存在")
                
                product.stock += quantity
            
            # 创建库存记录
            record = InventoryRecord(
                product_id=product_id,
                variant_id=variant_id,
                type=InventoryType.IN.value,
                quantity=quantity,
                notes=notes,
                operator_id=operator_id
            )
            
            db.session.add(record)
            db.session.commit()
            
            return record
            
        except NotFoundError:
            db.session.rollback()
            raise
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"入库操作失败: {str(e)}")
    
    @staticmethod
    def stock_out(product_id, quantity, variant_id=None, notes='', operator_id=None):
        """出库操作"""
        if not product_id or not quantity or quantity <= 0:
            raise ValidationError("请提供有效的商品ID和出库数量")
        
        try:
            # 更新库存
            if variant_id:
                variant = ProductVariant.query.get(variant_id)
                if not variant:
                    raise NotFoundError("商品变体不存在")
                
                if variant.stock < quantity:
                    raise ValidationError("库存不足")
                
                variant.stock -= quantity
                product = variant.product
            else:
                product = Product.query.get(product_id)
                if not product:
                    raise NotFoundError("商品不存在")
                
                if product.stock < quantity:
                    raise ValidationError("库存不足")
                
                product.stock -= quantity
            
            # 创建库存记录
            record = InventoryRecord(
                product_id=product_id,
                variant_id=variant_id,
                type=InventoryType.OUT.value,
                quantity=quantity,
                notes=notes,
                operator_id=operator_id
            )
            
            db.session.add(record)
            db.session.commit()
            
            return record
            
        except (NotFoundError, ValidationError):
            db.session.rollback()
            raise
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"出库操作失败: {str(e)}")
    
    @staticmethod
    def adjust_stock(product_id, quantity, variant_id=None, notes='', operator_id=None):
        """库存调整"""
        if not product_id or quantity is None:
            raise ValidationError("请提供有效的商品ID和调整数量")
        
        if not notes:
            raise ValidationError("请提供库存调整原因")
        
        try:
            # 更新库存
            if variant_id:
                variant = ProductVariant.query.get(variant_id)
                if not variant:
                    raise NotFoundError("商品变体不存在")
                
                if variant.stock + quantity < 0:
                    raise ValidationError("调整后库存不能小于0")
                
                variant.stock += quantity
                product = variant.product
            else:
                product = Product.query.get(product_id)
                if not product:
                    raise NotFoundError("商品不存在")
                
                if product.stock + quantity < 0:
                    raise ValidationError("调整后库存不能小于0")
                
                product.stock += quantity
            
            # 创建库存记录
            record_type = InventoryType.IN.value if quantity > 0 else InventoryType.OUT.value
            record = InventoryRecord(
                product_id=product_id,
                variant_id=variant_id,
                type=record_type,
                quantity=abs(quantity),
                notes=notes,
                operator_id=operator_id
            )
            
            db.session.add(record)
            db.session.commit()
            
            return record
            
        except (NotFoundError, ValidationError):
            db.session.rollback()
            raise
        except Exception as e:
            db.session.rollback()
            raise ValidationError(f"库存调整失败: {str(e)}") 